package com.pactera.asmp.server.restfullapi;

import com.alibaba.fastjson.JSONObject;
import com.pactera.asmp.server.common.annotations.JwtIgnore;
import com.pactera.asmp.server.common.constants.PermissionCode;
import com.pactera.asmp.server.common.email.IMailService;
import com.pactera.asmp.server.common.logprint.utils.StringUtils;
import com.pactera.asmp.server.entity.ResponseResult;
import com.pactera.asmp.server.entity.TaskDTO;
import com.pactera.asmp.server.entity.TaskSearchDTO;
import com.pactera.asmp.server.pojo.ScriptInfo2;
import com.pactera.asmp.server.service.ScreenDataService;
import com.pactera.asmp.server.service.TaskService;
import com.pactera.asmp.server.utils.DateUtil;
import com.pactera.asmp.server.vo.ExcelReportRequest;
import com.pactera.asmp.server.vo.PackageRecord;
import com.pactera.asmp.server.vo.TaskCreateRequest;
import com.pactera.asmp.server.vo.TestExceptionInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/api/v1/task")
public class RestfullTaskApi {

    private static final Logger logger = LoggerFactory.getLogger(RestfullTaskApi.class);

    @Autowired
    private TaskService taskService;

    @Autowired
    private ScreenDataService screenDataService;

    @RequiresPermissions({PermissionCode.TEST_TASK})
    @GetMapping
    public ResponseResult getTaskList(@RequestParam("projectId") Integer projectId,@RequestParam(value = "pageNum",required = false,defaultValue = "") Integer pageNum
            ,@RequestParam(value = "pageSize",required = false,defaultValue = "10") Integer pageSize
            ,@RequestParam(value = "name",required = false,defaultValue = "") String name
            ,@RequestParam(value = "status",required = false,defaultValue = "") Integer status
            ,@RequestParam(value = "type",required = false,defaultValue = "") Integer type
    ) {
        logger.info("GET /api/v1/task  getTaskList");
        TaskSearchDTO searchDTO = new TaskSearchDTO(null,projectId,name,type,null,null,status,null,null, null, null, null, null);
        searchDTO.setPageNum(pageNum);
        searchDTO.setPageSize(pageSize);
        return ResponseResult.defaultSuccess(taskService.getTaskList(searchDTO));
    }


    @RequiresPermissions({PermissionCode.TEST_TASK})
    @GetMapping(value = "/{masterComputerId}")
    public ResponseResult getTaskListByDuid(
            @PathVariable("masterComputerId") Integer masterComputerId
            ,@RequestParam(value = "projectId",required = false,defaultValue = "") Integer projectId
            ,@RequestParam(value = "exceDayStr",required = false,defaultValue = "") String exceDayStr
    ) {
        logger.info("GET /api/v1/task/{}  getTaskListByDuid", masterComputerId);
        Date startTime = null;
        Date endTime = null;
        if(StringUtils.isNotEmpty(exceDayStr)) {
            startTime = DateUtil.parseStrToDate(exceDayStr + " 0:00:00", DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
            endTime = DateUtil.parseStrToDate(exceDayStr + " 23:59:59", DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
        }
        if(null == projectId) {
            projectId = 0;
        }
        return ResponseResult.defaultSuccess(taskService.getTaskListByMasterComputerId(masterComputerId, projectId, startTime, endTime));
    }

    @GetMapping(value = "/scripts/{taskId}")
    public ResponseResult<List<ScriptInfo2>> getTaskScriptInfo(@PathVariable("taskId") Integer taskId) {
        logger.info("GET /api/v1/task/scripts/{}",taskId);
        List<ScriptInfo2> taskScriptInfo = taskService.getTaskScriptInfo(taskId);
        return ResponseResult.defaultSuccess(taskScriptInfo);
    }

    @RequiresPermissions({PermissionCode.TEST_TASK})
    @PostMapping(value = "")
    public ResponseResult newTaskSchedule(@RequestBody @Validated TaskDTO taskDTO) throws Exception {
        logger.info("POST /api/v1/task newTaskSchedule");
        return taskService.newTaskSchedule(taskDTO);
    }

    @RequiresPermissions({PermissionCode.TEST_TASK})
    @PostMapping(value = "/subtasks")
    public ResponseResult newTaskScheduleForDevices(@RequestBody @Validated TaskCreateRequest taskReq) throws Exception {
        logger.info("POST /api/v1/task/subtasks newTaskSchedule, duids:{}", JSONObject.toJSONString(taskReq.getDuidList()));
        return taskService.newTaskSchedule(taskReq);
    }

    @RequiresPermissions({PermissionCode.TEST_TASK})
    @PostMapping(value = "/reset")
    public ResponseResult resetTaskSchedule(@RequestBody @Validated TaskDTO taskDTO) throws Exception {
        logger.info("POST /api/v1/task/reset resetTaskSchedule");
        return taskService.resetTaskSchedule(taskDTO);
    }

    @RequiresPermissions({PermissionCode.TEST_TASK})
    @PutMapping(value = "/cancel/{id}",  produces = "application/json;charset=UTF-8")
    public ResponseResult cancelTask(@PathVariable("id") Integer id) {
        logger.info("PUT /api/v1/task/cancel/{}" ,id);
        return taskService.cancelTask(id);
    }

    @GetMapping(value = "/taskIng")
    public ResponseResult getTaskingByProjectId(@RequestParam("projectId") Integer projectId,@RequestParam(value = "pageNum",required = false,defaultValue = "1") Integer pageNum
            ,@RequestParam(value = "pageSize",required = false,defaultValue = "10") Integer pageSize) {
        logger.info("GET /api/v1/task  getTaskingByProjectId");
        TaskSearchDTO searchDTO = new TaskSearchDTO();
        searchDTO.setProjectId(projectId);
        searchDTO.setPageNum(pageNum);
        searchDTO.setPageSize(pageSize);
        return ResponseResult.defaultSuccess(screenDataService.getTaskingByProjectId(searchDTO));
    }

    @GetMapping(value = "/detail")
    public ResponseResult getTaskById(@RequestParam("taskId") Integer taskId) {
        logger.info("GET /api/v1/task/detail: {}",taskId);
        return ResponseResult.defaultSuccess(taskService.queryTaskById(taskId));
    }

    @Autowired
    private IMailService emailService;

    @GetMapping(value = "/email/{taskId}")
    public ResponseResult<List<ScriptInfo2>> emailMock(@PathVariable("taskId") Integer taskId) {
        logger.info("GET /api/v1/task/email/{}",taskId);
        //String[] toEmails, String[] ccEmails, String subject, String[] attachmentPath, String tamplateName, Map<String, Object> dataMap
        String[] toEmails=new String[]{"jin.xu12@gientech.com"};
        String[] ccEmails=new String[]{};
        String subject="subject";
        String[] attachmentPath = new String[]{};
        String tamplateName = "asmp_email_template.html";
        Map<String, Object> dataMap = new HashMap<>();
        //dataMap build
        List<TestExceptionInfo> teList = new ArrayList<>();
        TestExceptionInfo te = new TestExceptionInfo();
        te.setProcessName("aaaTest");
        te.setAnrCount(1);
        te.setCrashCount(2);
        te.setOtherCount(3);
        teList.add(te);
        dataMap.put("exceptiondata",  teList);
        dataMap.put("version","1.11");
        dataMap.put("crashPrcoessCount",11);
        dataMap.put("allAnrCount", 22);
        dataMap.put("allCrashCount", 33);
        dataMap.put("allOtherCount", 44);
        try {
            emailService.sendBatchMailByTemplate(toEmails, ccEmails, subject,
                    attachmentPath, tamplateName, dataMap, null,"");
        } catch (Exception e) {
            logger.error("emailMock error: ",e);
        }
        return ResponseResult.defaultSuccess(null);
    }

    @RequiresPermissions({PermissionCode.TEST_TASK})
    @DeleteMapping(value = "/remove/{id}",  produces = "application/json;charset=UTF-8")
    public ResponseResult deleteTask(@PathVariable("id") Integer id) {
        logger.info("PUT /api/v1/task/remove/{}" ,id);
        return taskService.removeTask(id);
    }

    @RequiresPermissions({PermissionCode.TEST_TASK})
    @PostMapping(value = "/export/{taskId}",  produces = "application/json;charset=UTF-8")
    public void exportPdf(@PathVariable("taskId") Integer taskId, HttpServletResponse response) {
        logger.info("POST /export/{}" ,taskId);
        taskService.exportPdf(taskId, response);
    }

//    @RequiresPermissions({PermissionCode.TEST_TASK})
//    @GetMapping(value = "/report-performance-info", produces = "application/json;charset=UTF-8")
//    public ResponseResult getReportPerformanceInfo(@RequestParam("taskId") Integer taskId) {
//        logger.info("/api/v1/task/report-performance-info reportPerformanceInfo taskId:{}" ,taskId);
//        return  taskService.getReportPerformanceInfo(taskId);
//    }

    @JwtIgnore
    @RequestMapping(value = "/export-memory-report", method = RequestMethod.POST)
    public void exportMemoryReport(@RequestBody ExcelReportRequest reportRequest, HttpServletResponse response) {
        logger.info("POST /export/{}" ,reportRequest.getTaskId());
        taskService.exportMemoryReport(reportRequest.getTaskId(), response);
    }

    //@RequiresPermissions({PermissionCode.TEST_TASK})
    @JwtIgnore
    @RequestMapping(value = "/export-top-report", method = RequestMethod.POST)
    public void exportTopReport(@RequestBody ExcelReportRequest reportRequest, HttpServletResponse response) {
        logger.info("POST /export/{}" ,reportRequest.getTaskId());
        taskService.exportTopReport(reportRequest.getTaskId(), response);
    }

    @JwtIgnore
    @RequestMapping(value = "/export-hmi-report", method = RequestMethod.POST)
    public void exportHMIReport( @RequestBody ExcelReportRequest reportRequest,HttpServletResponse response) {
        logger.info("POST /export/" );
        taskService.exportHmiReport(reportRequest, response);
    }

    @JwtIgnore
    @RequestMapping(value = "/add-package-record", method = RequestMethod.POST)
    public ResponseResult addPackageRecord(@RequestBody PackageRecord packageRecord) {
        logger.info("POST /add-package-record" );
        return taskService.addPackageRecord(packageRecord);
    }

    @JwtIgnore
    @RequestMapping(value = "/del-package-record", method = RequestMethod.POST)
    public ResponseResult delPackageRecord( @RequestBody PackageRecord packageRecord) {
        logger.info("POST /" );
        return taskService.delPackageRecord(packageRecord);
    }

    @JwtIgnore
    @RequestMapping(value = "/select-package-record", method = RequestMethod.POST)
    public ResponseResult queryPackageRecord(@RequestBody PackageRecord packageRecord) {
        logger.info("POST /" );
        return taskService.queryPackageRecord(packageRecord);
    }


//    @JwtIgnore
//    @RequestMapping(value = "/export-hmi-report/{taskId}", method = RequestMethod.POST)
//    public void exportHMIReport2(@PathVariable("taskId") Integer taskId, HttpServletResponse response) {
//        logger.info("POST /export/{}" ,taskId);
//        taskService.exportHmiReport(taskId, response);
//    }
}
